package com.iflytek.ci.common.support;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

/**
 * 用于解析xml文件的节点
 * @author mdzhang
 *
 */
public class XMLNodeParser {
	/** 日志信息 */
	private static final Logger logger = LoggerFactory
			.getLogger(XMLNodeParser.class);

	@SuppressWarnings("finally")
	public String getTextContent(File file, String node_path) {
		String context = "";
		try {
			if (file.exists()&&file.isFile()) {
				DocumentBuilderFactory domFactory = DocumentBuilderFactory
						.newInstance();
				DocumentBuilder builder = domFactory.newDocumentBuilder();
				Document doc = builder.parse(file);
				XPathFactory factory = XPathFactory.newInstance();
				XPath xpath = factory.newXPath();
				XPathExpression expr;
				expr = xpath.compile(node_path);
				Object result = expr.evaluate(doc, XPathConstants.NODESET);
				NodeList nodes = (NodeList) result;
				context=nodes.item(0).getTextContent();
			}else {
				logger.debug("文件没找到，可能已经删除或者文件路径错误");
			}
		} catch (XPathExpressionException e) {
			logger.debug("节点路径错误或没找到该节点");
			e.printStackTrace();
		} finally {
			return context;
		}
	}
}
